package com.miao.teacher.ui;

import java.text.DecimalFormat;

import org.json.JSONException;
import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;

import com.espeaker.sdk.Constants;
import com.espeaker.sdk.api.ReviseApi;
import com.espeaker.sdk.utils.JsonUtils;
import com.miao.teacher.adapter.RevisePageAdapter;
import com.miao.teacher.app.TApp;
import com.miao.teacher.presenters.OnOrderChange;
import com.miao.teacher.utils.FileUtil;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.AbsoluteSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ToggleButton;

public class MainFragment extends BaseFragment implements OnOrderChange{

	private TextView tvSalary;
	private TextView tvCount;
	private ReviseApi api = new ReviseApi();

	private ViewPager mPagerVp;

	private RevisePageAdapter mPageAdapter=null;
	
	private ImageView image;
	private TextView view1, view2;
	private int currIndex;// 当前页卡编号
	private int bmpW;// 横线图片宽度
	private int offset;// 图片移动的偏移量
	
	private float percent = 0; // for reward animation
	private Runnable rewardRunnable; // for reward animation

	private ToggleButton tBtnAlert;
	public static MainFragment newInstance() {
		MainFragment fragment = new MainFragment();
		return fragment;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.layout_main, null);
		tvSalary = (TextView) view.findViewById(R.id.tvSalary);
		tvCount = (TextView) view.findViewById(R.id.tvCount);
		InitTextView(view);
		InitImage(view);
		InitViewPager(view);
		tBtnAlert=(ToggleButton) view.findViewById(R.id.tBtn_alert);
		tBtnAlert.setOnCheckedChangeListener(new ToggleButton.OnCheckedChangeListener()  
        {  
			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if(isChecked)
				{
					JPushInterface.resumePush(getActivity().getApplicationContext());
					FileUtil.addPreferences(getActivity(), TApp.PUSH_KEY, "1");
				}else
				{
					JPushInterface.stopPush(getActivity().getApplicationContext());
					FileUtil.addPreferences(getActivity(), TApp.PUSH_KEY, "0");
				}
			}  
        }); 
		String push = FileUtil.getPreferences(getActivity(), TApp.PUSH_KEY);
		if(push==null||push.equals("1"))
		{
			tBtnAlert.setChecked(true);
		}else
		{
			tBtnAlert.setChecked(false);
		}
		return view;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		String userId = FileUtil.getPreferences(getActivity(), TApp.USER_ID);
		api.getSalary(userId, mHandler);
		
		//InitViewPager();
		
	}

	@Override
	protected void RecMsgFromHandler(Message msg) {
		// TODO Auto-generated method stub
		super.RecMsgFromHandler(msg);
		switch (msg.what) {
		case Constants.REVISE_GET_SALARY:
			setSalary(msg.obj);
			break;
		}
	}
	/* 
     * 初始化标签名 
     */  
    public void InitTextView(View view){  
        view1 = (TextView)view.findViewById(R.id.tv_guid1);  
        view2 = (TextView)view.findViewById(R.id.tv_guid2);   
        view1.setOnClickListener(new txListener(0));  
        view2.setOnClickListener(new txListener(1));  
    }  
    public class txListener implements View.OnClickListener{  
        private int index=0;  
          
        public txListener(int i) {  
            index =i;  
        }  
        @Override  
        public void onClick(View v) {  
            // TODO Auto-generated method stub  
        	mPagerVp.setCurrentItem(index);  
        }  
    }
    /* 
     * 初始化图片的位移像素 
     */  
    public void InitImage(View view){  
        image = (ImageView)view.findViewById(R.id.cursor); 
        bmpW=getXPx()/2;
        LayoutParams lp=image.getLayoutParams();
        lp.height=4;
        lp.width=bmpW;
        image.setLayoutParams(lp);
        image.setBackgroundColor(Color.argb(255, 106, 180, 159)); 
    }
    
    /* 
     * 初始化ViewPager 
     */  
    public void InitViewPager(View view){  
    	mPagerVp = (ViewPager) view.findViewById(R.id.vp_pager);
    	mPageAdapter=new RevisePageAdapter(getActivity().getBaseContext(),getChildFragmentManager(),this);
		mPagerVp.setAdapter(mPageAdapter);
		mPagerVp.setCurrentItem(0);//设置当前显示标签页为第一页  
		view1.performClick();
		mPagerVp.setOnPageChangeListener(new MyOnPageChangeListener());//页面变化时的监听器  
    }  
  
      
    public class MyOnPageChangeListener implements OnPageChangeListener{  
        private int one = bmpW;//两个相邻页面的偏移量  
          
        @Override  
        public void onPageScrolled(int arg0, float arg1, int arg2) {  
            // TODO Auto-generated method stub  
              
        }  
          
        @Override  
        public void onPageScrollStateChanged(int arg0) {  
            // TODO Auto-generated method stub  
              
        }  
          
        @Override  
        public void onPageSelected(int arg0) {  
            // TODO Auto-generated method stub  
            Animation animation = new TranslateAnimation(currIndex*one,arg0*one,0,0);//平移动画  
            currIndex = arg0;  
            animation.setFillAfter(true);//动画终止时停留在最后一帧，不然会回到没有执行前的状态  
            animation.setDuration(200);//动画持续时间0.2秒  
            image.startAnimation(animation);//是用ImageView来显示动画的  
            int i = currIndex + 1;  
        }  
    }

	/*
	 * 显示工资
	 */
	private void setSalary(Object obj) {
		try {
			JSONObject json = new JSONObject(obj.toString());
			int status = JsonUtils.getInt(json, "status", -1);
			if (status == 0) {
				JSONObject json2 = JsonUtils
						.getJSONObject(json, "values", null);
				int salary = JsonUtils.getInt(json2, "salary", 0);
				int num = JsonUtils.getInt(json2, "num", 0);
				tvCount.setText("(" + num + ")");
				//tvSalary.setText("￥" + salary);
				showSalary(salary);
				
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	// implement an animation
	private void showSalary(final int money) {
		percent = 0;
		rewardRunnable = new Runnable() {
			@Override
			public void run() {
				float rest = 100 - percent;
				percent += rest * rest / 110 + 0.04;
				DecimalFormat fnum = new DecimalFormat("##0.0");
				String curMoney = "￥"
						+ fnum.format((float) money * percent / 100);
				String showText = curMoney;
				SpannableStringBuilder sb = new SpannableStringBuilder(showText);
				sb.setSpan(new AbsoluteSizeSpan(70), 0, curMoney.length(),
						Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				tvSalary.setText(sb);
				if (percent < 100) {
					tvSalary.postDelayed(rewardRunnable, 10);
				} else {
					curMoney = "￥" + fnum.format((float) money);
					showText = curMoney;
					sb = new SpannableStringBuilder(showText);
					sb.setSpan(new AbsoluteSizeSpan(70), 0, curMoney.length(),
							Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
					tvSalary.setText(sb);
				}
			}
		};
		tvSalary.postDelayed(rewardRunnable, 10);
	}
	@Override
	public void onOrderStatusChange() {
		// TODO Auto-generated method stub
		if(mPageAdapter!=null)
		{
			((UnfinishedFragment)(mPageAdapter.fragment.get(1))).doReload();
		}
	}
}
